package com.bpz.main.directive;

import com.bpz.jxw.article.model.Article;
import com.bpz.jxw.article.service.IArticleService;
import com.bpz.main.model.ActMsg;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.Map;

/**
 * Created by 半瓶子 on 2/10/15.
 * blog: xusir.cnblogs.com
 */
public class ArticleListDirective implements TemplateDirectiveModel {
    @Autowired
    IArticleService articleService;

    @Override
    public void execute(Environment env, Map map, TemplateModel[] templateModels, TemplateDirectiveBody body) throws TemplateException, IOException {
        int pageIndex = Integer.parseInt(map.get("pageIndex") + "");
        int pageSize = Integer.parseInt(map.get("pageSize") + "");
        int interval = Integer.parseInt(map.get("interval") + "");
        int contentType = Integer.parseInt(map.get("contentType") + "");
        String order;
        switch (interval) {
            case 8:
                order = "reply";
                break;
            case 12:
                order = "id";
                break;
            case 24:
            case 24*7:
            case 24*30:
                order = "upper";
                break;
            default:
                order="id";
                break;

        }
        ActMsg<Article> actMsg = articleService.selectPage(interval, contentType, pageIndex, pageSize,order);
        actMsg.setTotal(articleService.count(interval, contentType));
      //  System.out.println(JSON.toJSONString(actMsg));
        env.setVariable("articles", env.getObjectWrapper().wrap(actMsg));
        body.render(env.getOut());
    }
}
